//
//  YH_InfoSyncViewController.m
//  YinHang
//
//  Created by 123 on 14-6-30.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_InfoSyncViewController.h"

// 用户Id
#define UID [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"]

@interface YH_InfoSyncViewController ()
{
    UIImage *input_normalImg;
    UIImage *input_onImg;
    
    
    ASIFormDataRequest *provinceRequest;//地市
    ASIFormDataRequest *cityRequest;//频道
    ASIFormDataRequest *mokuaiRequest;//功能
    ASIFormDataRequest *mingpianRequest;//板块
    ASIFormDataRequest *infoSyncRequest;//提交
    
    NSArray *provinceData;//地市data（用于获取pid）
    NSString *pid;//地市id
    NSMutableArray *provinceArr;//地市名称数组
    
    NSArray *cityData;//频道data（用于获取cid）
    NSString *cid;//频道id
    NSMutableArray *cityArr;//频道名称数组
    
    NSArray *mokuaiData;//频道data（用于获取同步信息时的mid）
    NSString *mkid;//同步信息时的mid
    NSMutableArray *mokuaiArr;//功能名称数组
    
    NSArray *mingpianData;//小版块data（用于获取xtid）
    NSString *xtid;//小板块id
    NSMutableArray *mingpianArr;//板块名称数组
    
    BOOL isPlatformSync;//是否平台信息同步
    BOOL isWebSync;//是否网站间信息同步
    
    MBProgressHUD *loadHud;
    
    NSString *state;//第一次打开状态
}
@end

@implementation YH_InfoSyncViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    state = @"first";
    [self getFirstData];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"信息同步";
    self.navigationItem.hidesBackButton = YES;
//    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
//    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
//    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
//    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    [self setUI];

    
    isPlatformSync = YES;
    isWebSync = YES;
}

-(void)getFirstData{
    if ([state isEqualToString:@"first"]) {
        [self getAllProvince];
    }
}

- (void)setUI {
    NSArray *textFieldArr = @[_textField_1,_textField_2,_textField_3,_textField_4];
    input_normalImg = [UIImage imageNamed:@"input_normal"];
    input_onImg = [UIImage imageNamed:@"input_on"];
    for (UITextFieldPadding *textField in textFieldArr) {
        // 设置背景
        [textField setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
        // 设置文本颜色
        textField.textColor = TEXT_COLOR;
        // 设置文本偏移
        [textField setPadding:YES top:0 right:15 bottom:0 left:15];
    }
    
    UIImage *infoSyncBtn_bgImg = [UIImage imageNamed:@"infosync_infosyncbtn_bg"];
    [_infoSyncBtn setBackgroundImage:[infoSyncBtn_bgImg stretchableImageWithLeftCapWidth:infoSyncBtn_bgImg.size.width*0.5f topCapHeight:infoSyncBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    
    UIImage *directReturnBtn_bgImg = [UIImage imageNamed:@"infosync_directbackbtn_bg"];
    [_directReturnBtn setBackgroundImage:[directReturnBtn_bgImg stretchableImageWithLeftCapWidth:directReturnBtn_bgImg.size.width*0.5f topCapHeight:directReturnBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    
    // 适配屏幕
    if (!IPHONE5) {
        
        _containerView.frame = CGRectMake(_containerView.frame.origin.x, _containerView.frame.origin.y-10, _containerView.bounds.size.width, _containerView.bounds.size.height);
        
        _infoSyncBtn.frame = CGRectMake(_infoSyncBtn.frame.origin.x, _infoSyncBtn.frame.origin.y-10, _infoSyncBtn.bounds.size.width, _infoSyncBtn.bounds.size.height);
        _directReturnBtn.frame = CGRectMake(_directReturnBtn.frame.origin.x, _directReturnBtn.frame.origin.y-10, _directReturnBtn.bounds.size.width, _directReturnBtn.bounds.size.height);
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//平台信息同步
- (IBAction)platformSync:(id)sender {
    UIButton *btn = (UIButton*)sender;
    
    NSArray *catdownbtnArr = @[_catdownbtn_1,_catdownbtn_2,_catdownbtn_3,_catdownbtn_4];
    
    if (isPlatformSync == YES) {
        [btn setBackgroundImage:[UIImage imageNamed:@"choosebox"] forState:UIControlStateNormal];
        isPlatformSync = NO;
        
        for (UIButton *catdownbtn in catdownbtnArr) {
            [catdownbtn setBackgroundImage:[UIImage imageNamed:@"catdownbtn_normal"] forState:UIControlStateNormal];
            catdownbtn.enabled = NO;
        }
        
    } else {
        [btn setBackgroundImage:[UIImage imageNamed:@"choosebox_selected"] forState:UIControlStateNormal];
        isPlatformSync = YES;
        
        for (UIButton *catdownbtn in catdownbtnArr) {
            [catdownbtn setBackgroundImage:[UIImage imageNamed:@"catdownbtn_on"] forState:UIControlStateNormal];
            catdownbtn.enabled = YES;
        }
    }
}


// 如果没有选择地市
- (void)notGetAllProvince {
    [SVProgressHUD showErrorWithStatus:@"请选择地市！"];
    
    [_textField_2 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_textField_3 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_textField_4 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    
    [_textField_1 setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
    
    //return;
}

// 如果没有选择频道
- (void)notGetCity {
    [SVProgressHUD showErrorWithStatus:@"请选择频道！"];
    
    [_textField_1 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_textField_3 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_textField_4 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    
    [_textField_2 setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
    
    //return;
}

// 如果没有选择功能
- (void)notGetAllMokuai {
    [SVProgressHUD showErrorWithStatus:@"请选择功能！"];
    
    [_textField_1 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_textField_2 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_textField_4 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    
    [_textField_3 setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
    
    //return;
}

// 如果没有选择板块
- (void)notGetMingpianxtypelist {
    [SVProgressHUD showErrorWithStatus:@"请选择板块！"];
    
    [_textField_1 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_textField_2 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    [_textField_3 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
    
    [_textField_4 setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
    
    //return;
}


// 地市
- (void)getAllProvince {
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        // 提示正在加载数据
        //loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //loadHud.labelText = @"正在加载数据，请稍后...";

        
        /* 获取全部省份 */
        provinceRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        provinceRequest.requestMethod = @"POST";
        // 设置超时时间
        provinceRequest.timeOutSeconds = 30;
        provinceRequest.delegate = self;
        // 设置参数
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"getallprovince",@""];
        
        NSData *paramsData = [result toGBKEncodingData];
        provinceRequest.postBody = [paramsData mutableCopy];
        
        [provinceRequest startAsynchronous];
    }
}

// 频道
- (void)getCity {
    // 如果没有选择地市
    if ([NSString emptyValidate:_textField_1.text]) {
        //[self notGetAllProvince];
        
    } else {
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            // 提示正在加载数据
            //loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            //loadHud.labelText = @"正在加载数据，请稍后...";

            
            /* 获取频道 */
            cityRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
            cityRequest.requestMethod = @"POST";
            // 设置超时时间
            cityRequest.timeOutSeconds = 30;
            cityRequest.delegate = self;
            // 设置参数
            NSDictionary *paramsDict =  @{@"pid": pid};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"getcity",paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            cityRequest.postBody = [paramsData mutableCopy];
            
            [cityRequest startAsynchronous];
        }
    }
}

// 功能
- (void)getAllMokuai {
    // 如果没有选择地市
    if ([NSString emptyValidate:_textField_1.text]) {
        //[self notGetAllProvince];
        
    } else {
        // 如果没有选择频道
        if ([NSString emptyValidate:_textField_2.text]) {
            //[self notGetCity];
            
        } else {
            // 检查网络
            if (![Constants isExistenceNetwork]) {
                
            } else {
                // 提示正在加载数据
                //loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                //loadHud.labelText = @"正在加载数据，请稍后...";
                
                
                /* 获取会员类型 */
                mokuaiRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
                mokuaiRequest.requestMethod = @"POST";
                // 设置超时时间
                mokuaiRequest.timeOutSeconds = 60;
                mokuaiRequest.delegate = self;
                // 设置参数
                NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"getallmokuai",@""];
                
                NSData *paramsData = [result toGBKEncodingData];
                mokuaiRequest.postBody = [paramsData mutableCopy];
                
                [mokuaiRequest startAsynchronous];
            }
        }
    }
}

// 板块
- (void)mingPianXTypeList {
    // 如果没有选择地市
    if ([NSString emptyValidate:_textField_1.text]) {
        //[self notGetAllProvince];
        
    } else {
        // 如果没有选择频道
        if ([NSString emptyValidate:_textField_2.text]) {
            //[self notGetCity];
            
        } else {
            // 如果没有选择功能
            if ([NSString emptyValidate:_textField_3.text]) {
                //[self notGetAllMokuai];
                
            } else {
                // 检查网络
                if (![Constants isExistenceNetwork]) {
                    
                } else {
                    // 提示正在加载数据
                    //loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                    //loadHud.labelText = @"正在加载数据，请稍后...";
                    
                    /* 获取频道 */
                    mingpianRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
                    mingpianRequest.requestMethod = @"POST";
                    // 设置超时时间
                    mingpianRequest.timeOutSeconds = 60;
                    mingpianRequest.delegate = self;
                    // 设置参数
                    NSDictionary *paramsDict =  @{@"cid": cid, @"mid": mkid};
                    NSString *paramsStr = [NSString JSONString:paramsDict];
                    NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"mingpianxtypelist",paramsStr];
                    
                    NSData *paramsData = [result toGBKEncodingData];
                    mingpianRequest.postBody = [paramsData mutableCopy];
                    
                    [mingpianRequest startAsynchronous];
                }
            }
        }
    }
}


// 点击下拉按钮
- (IBAction)chooseType:(id)sender {
    UIButton *btn = (UIButton*)sender;
    state = @"notFirst";
    /* 请求相应的选择数据 */
    switch (btn.tag) {
        case 1://地市
            // 设置背景
            [_textField_2 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            [_textField_3 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            [_textField_4 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            
            [_textField_1 setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
            
            [self getAllProvince];
            
            break;
            
        case 2://频道
            [_textField_1 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            [_textField_3 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            [_textField_4 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            
            [_textField_2 setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
            
            [self getCity];
            
            break;
            
        case 3://功能
            [_textField_1 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            [_textField_2 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            [_textField_4 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            
            [_textField_3 setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
            
            [self getAllMokuai];
            
            break;
            
        case 4://板块
            [_textField_1 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            [_textField_2 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            [_textField_3 setBackground:[input_normalImg stretchableImageWithLeftCapWidth:input_normalImg.size.width*0.5f topCapHeight:input_normalImg.size.height*0.5f]];
            
            [_textField_4 setBackground:[input_onImg stretchableImageWithLeftCapWidth:input_onImg.size.width*0.5f topCapHeight:input_onImg.size.height*0.5f]];
            
            [self mingPianXTypeList];
            
            break;
            
        default:
            break;
    }
}



//网站间信息同步
- (IBAction)webSync:(id)sender {
    UIButton *btn = (UIButton*)sender;
    
    if (isWebSync == NO) {
        [btn setBackgroundImage:[UIImage imageNamed:@"choosebox_selected"] forState:UIControlStateNormal];
        isWebSync = YES;
    } else {
        [btn setBackgroundImage:[UIImage imageNamed:@"choosebox"] forState:UIControlStateNormal];
        isWebSync = NO;
    }
}

// 信息同步
- (IBAction)infoSyncBtnClick:(id)sender {
    if (!isPlatformSync && !isWebSync) {
        [SVProgressHUD showErrorWithStatus:@"请选择同步区域！"];
        return;
    }
    if (isPlatformSync) {
        if ([NSString emptyValidate:_textField_1.text]) {
            [self notGetAllProvince];
            return;
        }
        if ([NSString emptyValidate:_textField_2.text]) {
            [self notGetCity];
            return;
        }
        if ([NSString emptyValidate:_textField_3.text]) {
            [self notGetAllMokuai];
            return;
        }
        if ([NSString emptyValidate:_textField_4.text]) {
            [self notGetMingpianxtypelist];
            return;
        }
    }
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        // 提示正在加载数据
        loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        loadHud.labelText = @"正在同步，请稍后...";
        
        
        /* 提交同步信息请求 */
        
        infoSyncRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        infoSyncRequest.requestMethod = @"POST";
        // 设置超时时间
        infoSyncRequest.timeOutSeconds = 60;
        infoSyncRequest.delegate = self;
        // 设置参数
        NSDictionary *paramsDict;
        if (!isPlatformSync) {
            paramsDict = @{@"id":_newsId,@"mid":@"0",@"xtid":@"0",@"cid":UID,@"check1":@"0",@"check2":@"1"};//id同步信息id;mid模块id;xtid小板块id;cid用户账号cid;check1平台信息同步选中状态;check2网站间同步选中状态
            
            //paramsDict = @{@"id":_newsId,@"mid":@"0",@"xtid":@"0",@"cid":@"3027",@"check1":@"0",@"check2":@"1"};//id同步信息id;mid模块id;xtid小板块id;cid用户账号cid;check1平台信息同步选中状态;check2网站间同步选中状态
            //paramsDict = @{@"id":@"47315",@"mid":@"0",@"xtid":@"0",@"cid":@"3027",@"check1":@"0",@"check2":@"1"};
        } else {
            if (isWebSync) {
                //paramsDict = @{@"id":_newsId,@"mid":mkid,@"xtid":xtid,@"cid":@"3027",@"check1":@"1",@"check2":@"1"};//id同步信息id;mid模块id;xtid小板块id;cid用户账号cid;check1平台信息同步选中状态;check2网站间同步选中状态
                //paramsDict = @{@"id":_newsId,@"mid":mkid,@"xtid":xtid,@"cid":@"3027",@"check1":@"1",@"check2":@"1"};//id同步信息id;mid模块id;xtid小板块id;cid用户账号cid;check1平台信息同步选中状态;check2网站间同步选中状态
                paramsDict = @{@"id":_newsId,@"mid":mkid,@"xtid":xtid,@"cid":UID,@"check1":@"1",@"check2":@"1"};//id同步信息id;mid模块id;xtid小板块id;cid用户账号cid;check1平台信息同步选中状态;check2网站间同步选中状态
            } else {
                //paramsDict = @{@"id":_newsId,@"mid":mkid,@"xtid":xtid,@"cid":@"3027",@"check1":@"1",@"check2":@"0"};//id同步信息id;mid模块id;xtid小板块id;cid用户账号cid;check1平台信息同步选中状态;check2网站间同步选中状态
                paramsDict = @{@"id":_newsId,@"mid":mkid,@"xtid":xtid,@"cid":UID,@"check1":@"1",@"check2":@"0"};//id同步信息id;mid模块id;xtid小板块id;cid用户账号cid;check1平台信息同步选中状态;check2网站间同步选中状态
            }
        }
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, @"tongbuset",paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        infoSyncRequest.postBody = [paramsData mutableCopy];
        
        [infoSyncRequest startAsynchronous];
    }
}

#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    loadHud.hidden = YES;
    if (request == provinceRequest) {//地市
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                NSDictionary *info = result[@"info"];
                provinceData = info[@"data"];
                
                provinceArr = [NSMutableArray array];
                for (NSDictionary *dict in provinceData) {
                    NSString *province = dict[@"textvalue"];
                    [provinceArr addObject:province];
                }
                if ([state isEqualToString:@"first"] && provinceData.count != 0) {
                    _textField_1.text = provinceData[0][@"textvalue"];
                    pid = provinceData[0][@"idvalue"];
                    
                    [self getCity];
                }else{
                // 进入选择界面
                [self enterChoiceVCWithNavTitle:@"选择地市" SelectTag:1 DataArr:provinceArr];
               
                //_textField_2.text = nil;
                //_textField_4.text = nil;
                    state = @"first";
                }
                
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
        
    } else if (request == cityRequest) {//频道
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                NSDictionary *info = result[@"info"];
                cityData = info[@"data"];
                
                cityArr = [NSMutableArray array];
                for (NSDictionary *dict in cityData) {
                    NSString *city = dict[@"textvalue"];
                    [cityArr addObject:city];
                }
                if ([state isEqualToString:@"first"] && cityData.count != 0) {
                    _textField_2.text = cityData[0][@"textvalue"];
                    cid = cityData[0][@"idvalue"];
                    
                    [self getAllMokuai];
                }else{
                // 进入选择界面
                [self enterChoiceVCWithNavTitle:@"选择频道" SelectTag:2 DataArr:cityArr];
                    state = @"first";
                }
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
        
    } else if (request == mokuaiRequest) {//功能
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                NSDictionary *info = result[@"info"];
                mokuaiData = info[@"data"];
                
                mokuaiArr = [NSMutableArray array];
                for (NSDictionary *dict in mokuaiData) {
                    NSString *mokuai = dict[@"textvalue"];
                    
                    [mokuaiArr addObject:mokuai];
                }
                if ([state isEqualToString:@"first"] && mokuaiData.count != 0) {
                    _textField_3.text = mokuaiData[0][@"textvalue"];
                    mkid = mokuaiData[0][@"idvalue"];
                    
                    [self mingPianXTypeList];
                }else{
                // 进入选择界面
                [self enterChoiceVCWithNavTitle:@"选择功能" SelectTag:3 DataArr:mokuaiArr];
                    state = @"first";
                }
                
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
        
    } else if (request == mingpianRequest) {//板块
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                NSDictionary *info = result[@"info"];
                mingpianData = info[@"data"];
                
                mingpianArr = [NSMutableArray array];
                for (NSDictionary *dict in mingpianData) {
                    NSString *mingpian = dict[@"xtname"];
                    [mingpianArr addObject:mingpian];
                }
                if ([state isEqualToString:@"first"] && mingpianData.count != 0) {
                    _textField_4.text = mingpianData[0][@"xtname"];
                    xtid = mingpianData[0][@"xtid"];
                }else{
                // 进入选择界面
                [self enterChoiceVCWithNavTitle:@"选择板块" SelectTag:4 DataArr:mingpianArr];
                }
                
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
        
    } else if(request == infoSyncRequest) {
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [loadHud hide:YES];
                
                // 信息同步成功
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"同步成功" message:@"是否继续同步？" delegate:self cancelButtonTitle:@"直接返回" otherButtonTitles:@"继续同步", nil];
                [alert show];
                
                
            } else {
                [loadHud hide:YES];
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
            
        } else {
            [loadHud hide:YES];
            [SVProgressHUD showErrorWithStatus:@"数据解析出错"];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [loadHud hide:YES];
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


#pragma mark - enterChoiceVC

- (void)enterChoiceVCWithNavTitle:(NSString*)navTitle SelectTag:(NSInteger)selectTag DataArr:(NSArray*)dataArr {
    
    ChoicesTableViewController *choicesVC = [[ChoicesTableViewController alloc]init];
    choicesVC.choiceDelegate = self;
    
    choicesVC.title = navTitle;
    choicesVC.tag_ = selectTag;
    choicesVC.dataArr = dataArr;
    [choicesVC.tableView reloadData];
    
    UINavigationController *choicesNav = [[UINavigationController alloc]initWithRootViewController:choicesVC];
    [self presentViewController:choicesNav animated:YES completion:nil];
    choicesNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:22.0]};
    
    if (MAIN_VERSION >= 7) {
        choicesNav.navigationBar.barTintColor = APP_COLOR;
        
    } else {
        choicesNav.navigationBar.tintColor = APP_COLOR;
    }
}


#pragma mark - ShowChoiceDelegate

- (void)showChoice:(NSString*)choice SelectedIndex:(NSInteger)selectedIndex Tag:(NSInteger)tag {
    switch (tag) {
        case 1://地市
            
            _textField_1.text = choice;
            _textField_2.text = nil;
            _textField_4.text = nil;
            
            pid = provinceData[selectedIndex][@"idvalue"];
            [self getCity];
            [self getAllMokuai];
            [self mingPianXTypeList];
            break;
        case 2://频道
            
            _textField_2.text = choice;
            _textField_4.text = nil;
            
            cid = cityData[selectedIndex][@"idvalue"];
            [self getAllMokuai];
            [self mingPianXTypeList];
            break;
        case 3://功能
            
            _textField_3.text = choice;
            
            mkid = mokuaiData[selectedIndex][@"idvalue"];
            [self mingPianXTypeList];
            break;
        case 4://模块
            
            _textField_4.text = choice;
            
            xtid = mingpianData[selectedIndex][@"xtid"];
            
            break;
            
        default:
            break;
    }
}



#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {//直接返回
        [self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] -3)] animated:YES];
    } else {//继续同步
        
    }
}


// 直接返回
- (IBAction)directReturnBtnClick:(id)sender {
    [provinceRequest cancel];
    [cityRequest cancel];
    [mokuaiRequest cancel];
    [mingpianRequest cancel];
    
    [self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] -3)] animated:YES];
}

//// 返回
//- (void)back {
//    [self.navigationController popViewControllerAnimated:YES];
//}

@end
